package com.zziq.cloudpicturebank.job.cycle;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import com.zziq.cloudpicturebank.constant.RabbitMqConstant;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.model.entity.Picture;
import com.zziq.cloudpicturebank.service.PictureService;
import com.zziq.cloudpicturebank.utils.ColorSimilarUtils;
import com.zziq.cloudpicturebank.utils.KMeansColorExtractor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.context.annotation.DependsOn;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.awt.*;
import java.net.URL;
import java.util.List;


@Slf4j
@Component
@DependsOn("mqInitMain")
public class MyMessageConsumer {
    @Resource
    private PictureService pictureService;

    /**
     * 指定程序监听的消息队列和确认机制
     *
     * @param pictureId
     * @param channel
     * @param deliveryTag
     */

    @SneakyThrows
    @RabbitListener(queues = {RabbitMqConstant.CALCULATE_PICCOLOR_QUEUE}, ackMode = "MANUAL")
    public void receiveMessage(Long pictureId, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", pictureId);
        try {
            //消费消息
            //获取图片对象
            Picture picture = pictureService.getById(pictureId);
            //更新图片颜色
            Color dominantColor =
                    KMeansColorExtractor.getDominantColor(new URL(picture.getOriginUrl()), 3);
            String colorHexColor = ColorSimilarUtils.getColorHexColor(dominantColor);
            picture.setPicColor(colorHexColor);
            pictureService.updateById(picture);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, false);
            //发生异常
            //todo 可设置死信交换机
            log.error("消息处理异常", e);
            throw new RuntimeException(e);
        }
    }
}
